package com.zx._09_架构.rpc演变过程.rpc_06;

import com.zx._09_架构.rpc演变过程.service.AccountService;
import com.zx._09_架构.rpc演变过程.service.UserService;
import com.zx._09_架构.rpc演变过程.service.impl.AccountServiceImpl;
import com.zx._09_架构.rpc演变过程.service.impl.UserServiceImpl;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Server {

    // 初始化所有接口的实现类，进行与接口名字的映射
    private static final Map<String, Object> SERVER_MAP = new HashMap<String, Object>();

    static {
        SERVER_MAP.put(UserService.class.getName(), new UserServiceImpl());
        SERVER_MAP.put(AccountService.class.getName(), new AccountServiceImpl());
    }

    // 模拟spring getBean
    public static Object getBean(String className) {
        return SERVER_MAP.get(className);
    }


    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(8888);
        Socket socket = null;
        while ((socket = ss.accept()) != null) {
            process(socket);
            socket.close();
        }
        ss.close();
    }

    public static void process(Socket socket) throws Exception {
        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());

        String className = input.readUTF();
        String methodName = input.readUTF();
        Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
        Object[] args = (Object[]) input.readObject();

        // 从注册好的服务中，找到服务
        Object impl = SERVER_MAP.get(className);
        Method method = impl.getClass().getMethod(methodName, parameterTypes);
        Object object = method.invoke(impl, args);

        log.info("provider = {}", object.toString());
        // 将结果写回去
        output.writeObject(object);
        output.flush();
    }
}
